package com.shopping_back.serviceImpl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shopping_back.pojo.entity.Delivery;
import com.shopping_back.mapper.DeliveryMapper;
import com.shopping_back.service.IDeliveryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * <p>
 * 物流主表 服务实现类
 * </p>
 *
 * @author Jack
 * @since 2025-07-12
 */
@Service
@RequiredArgsConstructor
public class DeliveryServiceImpl extends ServiceImpl<DeliveryMapper, Delivery> implements IDeliveryService {
    private final DeliveryMapper mapper;

    @Override
    public IPage<Delivery> list(Long userId,int page,int size){
        return mapper.selectPage(
                new Page<>(page,size),
                Wrappers.<Delivery>lambdaQuery()
                        .inSql(Delivery::getOrderId,
                                "SELECT id FROM order_main WHERE user_id="+userId)
        );
    }

    @Override
    public Delivery detail(String sn){
        Delivery d = mapper.selectOne(
                Wrappers.<Delivery>lambdaQuery().eq(Delivery::getDeliverySn,sn));
        if(d==null) throw new RuntimeException("物流单不存在");
        return d;
    }

    /** 用户确认收货 */
    @Transactional
    @Override
    public void confirm(String sn){
        int n = mapper.update(null,
                Wrappers.<Delivery>lambdaUpdate()
                        .eq(Delivery::getDeliverySn,sn)
                        .eq(Delivery::getStatus,1)          // 仅允许“运输中”确认
                        .set(Delivery::getStatus,2));
        if(n!=1) throw new RuntimeException("确认收货失败：状态不合法");
    }
}
